import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import axios from "axios";
import Spin from "@/utils/loading";
import { message } from "ant-design-vue";
import router from "@/router";

class HttpClient {
  private instance: AxiosInstance;

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);

    // 请求拦截
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 添加token等逻辑
        Spin.show("加载中...");
        return config;
      },
      (error) => Promise.reject(error),
    );

    // 响应拦截
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        // 统一处理响应数据
        const req = response.data;
        Spin.hide();
        if (!req.success) {
          switch (req.error.code) {
            case 404:
              message.warning("Hello, Ant Design Vue!").then((r) => r);
          }
        } else {
          switch (req.data.code) {
            case 200:
              return req.data.data;
            case 400:
              message.error("Hello, Ant Design Vue!").then((r) => r);
              break;
          }
        }
        return req.data.data;
      },
      (error) => {
        const errData = error.response?.data;
        switch (error.status) {
          case 422:
            message.error(errData.error.message).then((r) => r);
            break;
          case 404:
            message.warning(errData.error.message).then((r) => r);
            router.push("/404");
            break;
          case 500:
            message.error(errData.error.message).then((r) => r);
            break;
        }
        Spin.hide();
        // 统一错误处理
        return Promise.reject(error.message || error);
      },
    );
  }

  public request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config);
  }

  public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config);
  }

  public post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return this.instance.post(url, data, config);
  }

  // 其他方法同理...
}

// 默认配置
const defaultConfig: AxiosRequestConfig = {
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json",
  },
};

export const http = new HttpClient(defaultConfig);
